package com.example.bookstore.security.relam;

import com.example.bookstore.entity.BookUser;
import com.example.bookstore.mapper.BookUserMapper;
import com.example.bookstore.mapper.UserRoleMapper;
import com.example.bookstore.token.LoginToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

public class UserRealm extends AuthorizingRealm {

    public static String realmName = "UserRealm";

    public static String getRealmName() {
        return realmName;
    }

    @Autowired
    BookUserMapper userMapper;

    @Autowired
    UserRoleMapper userRoleMapper;


    /**
     * 执行授权逻辑
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行用户授权逻辑");
        Set<String> perms = new HashSet<>();
        BookUser user = (BookUser) principalCollection.getPrimaryPrincipal ();
        //给资源进行授权
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //给资源添加授权字符串
//        info.addStringPermission("add");
//        Subject subject = SecurityUtils.getSubject();
//        User user = (User) subject.getPrincipal();
        info.setStringPermissions (user.getPerms ());
        return info;
    }

    /**
     * 执行认证逻辑
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行用户认证逻辑");
        LoginToken token = (LoginToken) authenticationToken;
        //通过数据库获取包含token当中用户信息的用户
        BookUser user = userMapper.SelectByLoginName (token.getUsername ());
        if (user == null){
            return null;
        }
        Set<String> perms = new HashSet<> ();
        //获取用户的角色权限
        perms.add(userRoleMapper.SelectRoleById(user.getuserRole()));
        //添加到user的属性当中
        user.setPerms (perms);
        //返回用户信息
        return new SimpleAuthenticationInfo (user,user.getPassword(),getRealmName ());
    }
}
